#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Log.hpp"

void usage(const char *process)
{
    std::cout << "usage: \n\t";
    std::cout << process << " server_ip server_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    std::string server_ip = argv[1];
    // int server_port = std::stoi(argv[2]);
    // 可将类型直接写成uint16_t
    uint16_t server_port = std::stoi(argv[2]);

    sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);

    // std::string message;
    // char receive[1024];
    while (true)
    {
        int fd = socket(AF_INET, SOCK_STREAM, 0);
        if (fd < 0)
        {
            // std::cout << "socket error" << std::endl;
            // break;

            // 可输出到标准错误
            std::cerr << "socket error" << std::endl;
            // 因为循环结束就是函数结束，但为了保险，直接返回
            return 1;
        }
        bool isreconnect = false;
        int cnt = 5;
        do
        {
            int n = connect(fd, (const sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "client, connet error, reconnect: " << cnt << std::endl;
                --cnt;
                isreconnect = true;
                sleep(2);
            }
            else
            {
                // std::cout << "snow" << std::endl;
                break;
            }

        } while (cnt && isreconnect);

        if (cnt == 0 && isreconnect)
        {
            std::cerr << "client reconnect fail, user offline..." << std::endl;
            close(fd);
            break;
        }

        std::string message;
        char receive[4096]; // 大小可设置大一些

        std::cout << "enter your message:";
        std::getline(std::cin, message);
        ssize_t sz = write(fd, message.c_str(), message.size());
        if (sz < 0)
        {
            std::cerr << "write error" << std::endl;
        }
        sz = read(fd, receive, sizeof(receive));
        if (sz > 0)
        {
            receive[sz] = 0;
            std::cout << receive << std::endl;
        }
        else if (sz == 0)
        {
            std::cerr << "server[" << server_ip << ":" << server_port << "] quit" << std::endl;
            // break;        //不直接退出，让其重连
        }
        else
        {
            std::cerr << "read error" << std::endl;
        }

        // std::cout << "snow" << std::endl;
        close(fd);
        // std::cout << "snow" << std::endl;
    }

    return 0;
}